//
//  YHComposeImageView.swift
//  XLWB
//
//  Created by key on 16/7/3.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit

private let comCellId = "superCell"

class YHComposeImageView: UICollectionView {

    //声明闭包 点击cell调用
    var composeImageClosure: (() -> ())?
    
    //MARK: - 图片数据加载
    //存储图片数组
    var imageList: [UIImage] = [UIImage]()
    
    //记录图片
    var comCellImage: UIImage? {
        
        didSet{
            
            imageList.insert(comCellImage!, atIndex: 0)
            
            //加载图片的时候 显示图片 composeImageView
            hidden = false
            
            if imageList.count == 10 {
                
                imageList.removeAtIndex(0)
            }
            
            //刷新
            reloadData()
            
        }
    }
    
    //MARK: - 入口
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        
        backgroundColor = RGB(237, green: 237, blue: 237)
        
        //设置UI界面
        setUpUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: - 设置UI界面
    func setUpUI() {
        //设置代理对象
        delegate = self
        dataSource = self
        
        //设置flowLayout
        let flowLayout = collectionViewLayout as? UICollectionViewFlowLayout
        
        let itemMargin: CGFloat = 5
        let itemWH = (screenW - 20 - itemMargin * 2) / 3
        flowLayout?.itemSize = CGSize(width: itemWH, height: itemWH)
        
        flowLayout?.minimumInteritemSpacing = itemMargin
        flowLayout?.minimumLineSpacing = itemMargin
        
        //注册cell
        registerClass(YHComposeImageViewCell.self, forCellWithReuseIdentifier: comCellId)
        
    }
    

}

//MARK: - 数据源方法
extension YHComposeImageView: UICollectionViewDataSource,UICollectionViewDelegate {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        if imageList.count == 0 || imageList.count == 9 {
            
            return imageList.count
        }else{
            
            return imageList.count + 1
        }
        
    }
    
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = dequeueReusableCellWithReuseIdentifier(comCellId, forIndexPath: indexPath) as! YHComposeImageViewCell
        
        if indexPath.item == imageList.count {
        
            cell.img = nil
            
            return cell
        }
    
        cell.img = imageList[indexPath.item]
        
        
        //点击删除 删除指定图片
        cell.composeDeleteClosure = {[weak self] in
            
            self?.imageList.removeAtIndex(indexPath.item)
            
            
            //删除数组为空时 隐藏图片 composeImageView
            if self?.imageList.count == 0 {
                
                self?.hidden = true
            }
            
            
            self?.reloadData()
            
        }
        
        
        return cell
        
    }
    
    //点击cell
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        //取消选中状态
        collectionView.deselectItemAtIndexPath(indexPath, animated: true)
        
        //点击+号 跳转控制器
        if indexPath.item == imageList.count {
            
            //调用闭包  
            composeImageClosure?()
            
        }
        
        
    }
    
}



//MARK: - 自定义cell
class YHComposeImageViewCell: UICollectionViewCell {
    
    //声明闭包 点击删除按钮调用
    var composeDeleteClosure: (() -> ())?
    
    //接收数据
    var img: UIImage? {
        
        didSet {
            
            if img == nil {
                
                cellImageView.image = UIImage(named: "compose_pic_add")
                cellImageView.highlightedImage = UIImage(named: "compose_pic_add_highlighted")
                
                deleteButton.hidden = true
                
            }else{
                
                cellImageView.image = img
                
                deleteButton.hidden = false
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        //加载子控件
        addChildView()
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //MARK: - 自定义cell加载子控件
    //懒加载图片框
    lazy var cellImageView: UIImageView = UIImageView()
    
    //懒加载删除按钮
    lazy var deleteButton: UIButton = {
    
        let button = UIButton()
        
        button.addTarget(self, action: "deleteButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
        
        button.setBackgroundImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
        
        return button
    
    
    }()
    
    func addChildView() {
        
        //添加
        contentView.addSubview(cellImageView)
        contentView.addSubview(deleteButton)
        
        //约束
        cellImageView.snp_makeConstraints { (make) -> Void in
            
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
            
        }
        
        deleteButton.snp_makeConstraints { (make) -> Void in
            
            make.top.trailing.equalTo(contentView)
        }
        
    }
    
    
    //MARK: - 删除按钮点击事件
    func deleteButtonClick(btn: UIButton) {
        
        //调用删除闭包
        composeDeleteClosure?()
        
        
    }
}
